package com.ship.controller;

import com.ship.core.annotation.RequestDecryptBody;
import com.ship.core.annotation.ResponseEncryptBody;
import com.ship.entity.bo.Advert;
import com.ship.entity.bo.AppUpdate;
import com.ship.entity.bo.Users;
import com.ship.entity.dto.*;
import com.ship.jwt.JwtAuthenticationRequest;
import com.ship.jwt.JwtAuthenticationResponse;
import com.ship.service.AdvertService;
import com.ship.service.AppUpdateService;
import com.ship.service.AuthService;
import com.ship.service.UsersService;
import com.ship.util.ValidationUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.AuthenticationException;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.*;
import java.util.List;

@RestController
public class AuthController {

    @Value("${jwt.header}")
    private String tokenHeader;

    @Autowired
    private AuthService authService;

    private Logger logger = LoggerFactory.getLogger(UserController.class);

    @Autowired
    private AdvertService advertService;

    @Autowired
    private AppUpdateService appUpdateService;

    @RequestMapping(value = "${jwt.route.authentication.path}", method = RequestMethod.POST)
    @ResponseEncryptBody
    public JsonResult<UserInfoResponse> createAuthenticationToken(
            @RequestDecryptBody JsonRequest<JwtAuthenticationRequest> authenticationRequest,HttpServletRequest request) throws AuthenticationException {
        final UserInfoResponse token = authService.login(authenticationRequest,request);

        // Return the token
        return new JsonResult(ResultCode.SUCCESS,"登录成功",token);
    }

    @RequestMapping(value = "${jwt.route.authentication.refresh}", method = RequestMethod.GET)
    public ResponseEntity<?> refreshAndGetAuthenticationToken(
            HttpServletRequest request) throws AuthenticationException{
        String token = request.getHeader(tokenHeader);
        String refreshedToken = authService.refresh(token);
        if(refreshedToken == null) {
            return ResponseEntity.badRequest().body(null);
        } else {
            return ResponseEntity.ok(new JwtAuthenticationResponse(refreshedToken));
        }
    }

    @RequestMapping(value = "${jwt.route.authentication.register}", method = RequestMethod.POST)
    @ResponseEncryptBody
    public JsonResult register(@RequestDecryptBody  JsonRequest<Users> addedUser) throws AuthenticationException{
         Users users = authService.register(addedUser.getParameters());
         if(users == null){
             return new JsonResult(ResultCode.SYS_ERROR,"用户名已经存在");
         }else{
             Map<String,String> map = new HashMap<>();
             map.put("userId",users.getId());
             return new JsonResult(ResultCode.SUCCESS,"注册成功",map);
         }
    }


    @RequestMapping(value = "/auth/getAdvert", method = RequestMethod.POST)
    @ResponseEncryptBody
    public JsonResult getAdvert(@RequestDecryptBody JsonRequest<AdvertDto> dvertDto){
        logger.info("[广告信息]{}",dvertDto);
        JsonResult json = ValidationUtils.validateEntity(dvertDto.getParameters());
        if(json==null){
            JsonResult jsonResult = null;
            java.util.List<Advert> list = this.advertService.queryAdvert(dvertDto.getParameters().getType());
            List<AdvertResponse> advertResponseList = new ArrayList<>();
            for (Advert advert:list){
                AdvertResponse advertResponse = new AdvertResponse();
                advertResponse.setName(advert.getName());
                advertResponse.setUrl(advert.getUrl());
                advertResponse.setImagePath(advert.getImagePath()==null?"":advert.getImagePath());
                advertResponseList.add(advertResponse);
            }
            jsonResult = new JsonResult(ResultCode.SUCCESS, "成功",advertResponseList);
            logger.info("[广告返回]{}", jsonResult);
            return jsonResult;
        }
        return json;
    }

    @RequestMapping(value = "/auth/checkUpdate", method = RequestMethod.POST)
    @ResponseEncryptBody
    public JsonResult checkUpdate(@RequestDecryptBody JsonRequest<CheckUpdate> checkUpdate){
        JsonResult json = ValidationUtils.validateEntity(checkUpdate.getParameters());
        if(json==null){
            AppUpdate appUpdate = appUpdateService.checkUpdate(checkUpdate.getParameters().getVersion());
            return  new JsonResult(ResultCode.SUCCESS, "成功",appUpdate);
        }
        return json;
    }

    @RequestMapping({"auth/authCode"})
    public void getAuthCode(HttpServletRequest request, HttpServletResponse response, HttpSession session)
            throws IOException {
        int width = 63;
        int height = 37;
        Random random = new Random();
        //设置response头信息
        //禁止缓存
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);

        //生成缓冲区image类
        BufferedImage image = new BufferedImage(width, height, 1);
        //产生image类的Graphics用于绘制操作
        Graphics g = image.getGraphics();
        //Graphics类的样式
        g.setColor(this.getRandColor(200, 250));
        g.setFont(new Font("Times New Roman",0,28));
        g.fillRect(0, 0, width, height);
        //绘制干扰线
        for(int i=0;i<40;i++){
            g.setColor(this.getRandColor(130, 200));
            int x = random.nextInt(width);
            int y = random.nextInt(height);
            int x1 = random.nextInt(12);
            int y1 = random.nextInt(12);
            g.drawLine(x, y, x + x1, y + y1);
        }

        //绘制字符
        String strCode = "";
        for(int i=0;i<4;i++){
            String rand = String.valueOf(random.nextInt(10));
            strCode = strCode + rand;
            g.setColor(new Color(20+random.nextInt(110),20+random.nextInt(110),20+random.nextInt(110)));
            g.drawString(rand, 13*i+6, 28);
        }
        //将字符保存到session中用于前端的验证
        session.setAttribute("strCode", strCode);
        g.dispose();

        ImageIO.write(image, "JPEG", response.getOutputStream());
        response.getOutputStream().flush();

    }

    Color getRandColor(int fc,int bc){
        Random random = new Random();
        if(fc>255)
            fc = 255;
        if(bc>255)
            bc = 255;
        int r = fc + random.nextInt(bc - fc);
        int g = fc + random.nextInt(bc - fc);
        int b = fc + random.nextInt(bc - fc);
        return new Color(r,g,b);
    }
}
